package com.tsy.pointcloud.sse;

import com.tsy.common.annotation.Anonymous;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@RestController
@RequestMapping("/sse")
@CrossOrigin
public class SseController {

    private final SseService sseService;

    public SseController(SseService sseService) {
        this.sseService = sseService;
    }

    /**
     * 连接sse
     * @param clientId
     * @return
     */

    @GetMapping("/connect/{clientId}")
    @Anonymous
    public SseEmitter connect(@PathVariable String clientId) {
        return sseService.createEmitter(clientId);
    }

    /**
     * 测试推送
     * @throws IOException
     */
    @PostMapping("/push")
    @Anonymous
    public void push() throws IOException {
        for (int i = 0; i < 10; i++) {
            sseService.sendMessage("1", "Hello World" + i);
        }

    }

    /**
     * 关闭连接
     */
    @GetMapping("/disconnect/{clientId}")
    @Anonymous
    public void disconnect(@PathVariable String clientId) {
        sseService.disconnect(clientId);
    }





    private final ExecutorService executorService = Executors.newCachedThreadPool();

    @GetMapping(value = "/sse", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    @Anonymous
    public SseEmitter serverSentEvents() {
        SseEmitter emitter = new SseEmitter();
        try {
            // 向客户端发送一个初始事件
            emitter.send(SseEmitter.event().name("init").data("Connection established"));
            executorService.execute(() -> {
                try {

                    for (int i = 0; i < 10; i++) {
                        emitter.send(SseEmitter.event().data("Event " + i));
                        Thread.sleep(1000);
                    }
                    // 数据发送完毕，关闭连接
                    emitter.complete();
                } catch (IOException | InterruptedException e) {
                    emitter.completeWithError(e);
                }
            });
        } catch (IOException e) {
            emitter.completeWithError(e);
        }
        return emitter;
    }
}